package com.tititi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tititi.entity.Device;
import com.tititi.entity.MyPage;
import com.tititi.entity.Result;
import com.tititi.service.IFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.UUID;

/**
 * 文件服务
 * @author tang
 */
@Slf4j
@RestController
public class FileController {

    @Value("${file.path}")
    private String path;

    @Value("${file.url}")
    private String url;

    @Autowired
    private IFileService fileService;

    @RequestMapping("/download")
    public void download(
            //@PathVariable("dir") String dir,
            String filename,
            HttpServletResponse response
    ){
        response.setHeader("Content-Disposition","attachment;filename="+filename);
        response.setContentType("multipart/form-data");
        //String filePath = path + "/"+ dir+"/"+filename;
        String filePath = path + "/" +filename;

        File file=new File(filePath);
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        }
        OutputStream outputStream =null ;
        try {
            outputStream = response.getOutputStream();
            response.setContentLength((int) file.length());
            byte[] data = new byte[1024];
            int size = 0;
            while ((size = inputStream.read(data)) != -1) {
                outputStream.write(data, 0, size);
            }
            inputStream.close();
            outputStream.close();
        }catch (IOException e) {
            log.warn("file:{}, exception occur!",filePath);
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 上传文件
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping("/upload")
    public Result upload(MultipartFile file) throws  IOException{
        //生成名与目录
        String extensionName = StringUtils.substringAfter(file.getOriginalFilename(), ".");
        String dirName= DateFormatUtils.format(new Date(),"yyyy-MM-dd");
        String newFileName=UUID.randomUUID().toString().replace("-","");
        File dir=new File(path+'/'+dirName);
        if(!dir.exists()){dir.mkdirs();}
        //文件拷贝
        String newFilePath= dirName+'/'+newFileName+'.'+extensionName;
        File targetFile = new File(path +'/'+ newFilePath);
        file.transferTo(targetFile);
        //返回结果
        com.tititi.entity.File fileInfo=new com.tititi.entity.File();
        fileInfo.setName(file.getOriginalFilename());
        fileInfo.setUrl(url+newFilePath);
        return Result.ok(fileInfo);
    }



    @RequestMapping("/file/list")
    public Result upload(String fileTag,String fileName,Long current,Long size) {
        if(current==null || size==null){
            return Result.error("current or size can't be null");
        }
        IPage<com.tititi.entity.File> page=new Page<>();
        page.setCurrent(current);
        page.setSize(size);
        QueryWrapper<com.tititi.entity.File> queryWrapper=new QueryWrapper<>();
        queryWrapper
                .eq(!StringUtils.isBlank(fileTag),"tag",fileTag)
                .eq(!StringUtils.isBlank(fileName),"name",fileName)
                .orderByDesc("create_time");
        page = fileService.page(page, queryWrapper);
        return Result.ok(new MyPage<>(page.getRecords(), page.getTotal()));
    }

    @RequestMapping("/file/delete")
    public Result upload(Integer id) {
        fileService.removeById(id);
        return Result.ok();
    }

    @RequestMapping("/file/add")
    public Result upload(com.tititi.entity.File file) {
        if(StringUtils.isBlank(file.getTag()) || StringUtils.isBlank(file.getName() ) || StringUtils.isBlank(file.getUrl())){return Result.error("param can't be blank!");}
        fileService.save(file);
        return Result.ok();
    }

}
